package com.swotplus.admin.web.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swotplus.framework.web.BaseController;
import com.swotplus.common.annotation.Log;
import com.swotplus.common.constant.UserConstants;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.common.enums.BusinessType;
import com.swotplus.common.utils.EncryptionUtil;
import com.swotplus.framework.service.SysPasswordService;
import com.swotplus.framework.shiro.ShiroUtils;
import com.swotplus.system.sys.entity.SysUser;
import com.swotplus.system.sys.service.SysPostService;
import com.swotplus.system.sys.service.SysRoleService;
import com.swotplus.system.sys.service.SysUserService;
import com.swotplus.system.sys.vo.SysUserVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户信息
 * 
 * @author hugang
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    private String prefix = "system/user";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPostService sysPostService;

    @Autowired
    private SysPasswordService passwordService;

    /**
     * 跳转前端用户页面
     * @return
     */
    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(SysUserVo vo)
    {
        Page<SysUser> page=new Page<>(vo.getPage(),vo.getLimit());
        IPage<SysUser> pageList= sysUserService.selectUserList(page,vo);
        return AjaxResult.success("成功", (int) pageList.getTotal(),pageList.getRecords());
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", sysRoleService.list());
        mmap.put("posts", sysPostService.list());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user)
    {
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("login_name",user.getLoginName());

        QueryWrapper<SysUser> phoneWrapper=new QueryWrapper<>();
        phoneWrapper.eq("phonenumber",user.getPhonenumber());

        QueryWrapper<SysUser> emailWrapper=new QueryWrapper<>();
        emailWrapper.eq("email",user.getEmail());
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.count(queryWrapper)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.count(phoneWrapper)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(sysUserService.count(emailWrapper)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(sysUserService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") String userId, ModelMap mmap)
    {
        mmap.put("user", sysUserService.getById(userId));
        mmap.put("roles", sysRoleService.selectRolesByUserId(userId));
        mmap.put("posts", sysPostService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user)
    {

        if(user.getLoginName().equals("admin")){
            return  AjaxResult.error("不允许操作超级管理员用户");
        }
        QueryWrapper<SysUser> phoneWrapper=new QueryWrapper<>();
        phoneWrapper.eq("phonenumber",user.getPhonenumber());

        QueryWrapper<SysUser> emailWrapper=new QueryWrapper<>();
        emailWrapper.eq("email",user.getEmail());
        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.count(phoneWrapper)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(sysUserService.count(emailWrapper)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(sysUserService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") String userId, ModelMap mmap)
    {
        mmap.put("user", sysUserService.getById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user)
    {
        if(user.getLoginName().equals("admin")){
            return  AjaxResult.error("不允许操作超级管理员用户");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (sysUserService.updateById(user))
        {
            if (ShiroUtils.getUserId() == user.getId())
            {
                ShiroUtils.setSysUser(sysUserService.getById(user.getId()));
            }
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        try
        {
            return toAjax(sysUserService.removeById(ids));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user)
    {
        QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<>();
        sysUserQueryWrapper.eq("login_name",user.getLoginName());
        if(sysUserService.count(sysUserQueryWrapper)>0){
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user)
    {
        QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<>();
        sysUserQueryWrapper.eq("phonenumber",user.getPhonenumber());
        if(sysUserService.count(sysUserQueryWrapper)>0){
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user)
    {

        QueryWrapper<SysUser> sysUserQueryWrapper=new QueryWrapper<>();
        sysUserQueryWrapper.eq("email",user.getEmail());
        if(sysUserService.count(sysUserQueryWrapper)>0){
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user)
    {
        if(user.getId().equals("1")){
            return  AjaxResult.error("不允许操作超级管理员用户");
        }
        return toAjax(sysUserService.updateById(user));
    }


    @PostMapping("/unlock")
    @ResponseBody
    public AjaxResult unlock(String password)
    {
        try {
            SysUser sysUser=this.getUserInfo();
            System.out.println(EncryptionUtil.decrypt(sysUser.getPassword()));
            if (password.equals(EncryptionUtil.decrypt(sysUser.getPassword()))){
                return toAjax(true);
            }
        }catch (Exception e){
            return toAjax(false);
        }

        return toAjax(false);
    }


    @RequestMapping("/count")
    @ResponseBody
    public AjaxResult count()
    {
        return AjaxResult.success(sysUserService.count());
    }


}